import json
import logging
import os
import smtplib
from email import encoders
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from commons import request_data
from utils.func_utils import DBUtils, RequestUtils


class SendEmail:

    def send_email(self, subject, file_name) -> None:
        logging.info('邮件开始发送测试报告，入参为：%s' % file_name)

        msg_from = "lidongwei@songguo7.com"
        passwd = 'ldw@1234'
        msg_to = ",".join(f"{i}@songguo7.com" for i in request_data.EMAIL_TO)

        # 创建邮件内容
        msg = MIMEMultipart()
        msg['From'] = msg_from
        msg['To'] = msg_to
        msg['Subject'] = Header(subject, 'utf-8')
        msg.attach(MIMEText("正文：测试完毕，请查收附件！", 'plain', 'utf-8'))

        # 添加附件
        with open(file_name, 'rb') as f:
            att = MIMEApplication(f.read(), name=file_name)
            encoders.encode_base64(att)
            att.add_header('Content-Disposition', 'attachment', filename=file_name)
            msg.attach(att)

        try:
            with smtplib.SMTP_SSL("smtp.songguo7.com") as s:
                s.login(msg_from, passwd)
                print("准备发送邮件")
                s.sendmail(msg_from, msg['To'].split(','), msg.as_string())
                logging.info(f'邮件 {file_name} 发送成功，已发送至 {msg_to} 请查收!')
                print(f'邮件 {os.path.basename(file_name)} 发送成功，已发送至 {msg_to} 请查收!')
        except Exception as e:
            logging.error(f'邮件 {file_name} 发送失败，message: {e}')
        finally:
            s.quit()


def send_dingding_msg(text, notify_url):
    print("jinruding")
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    data = {
        "msgtype": "text",
        "text": {
            "content": text
        },
        "at": {
            "atMobiles": [
                ""
            ],
            "isAtAll": False
        }
    }
    print(data)
    data = json.dumps(data)
    response = RequestUtils().all_request(url=notify_url, method="POST", data=data, headers=headers)
    print(response.json())


if __name__ == '__main__':
    file_name = "车辆信息_20241114_130747.xlsx"
    SendEmail().send_email(file_name)
